﻿using Microsoft.Extensions.Logging;
using RBAC.MaHaiBo.Entity;
using RBAC.MaHaiBo.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace RBAC.MaHaiBo.Service
{
    /// <summary>
    /// 用户与角色关联服务层
    /// </summary>
    public class UserRoleService : IUserRoleService
    {
        /// <summary>
        /// 日志
        /// </summary>
        ILogger<UserRoleService> logger;
        /// <summary>
        /// 用户与角色关联仓储
        /// </summary>
        IUserRoleRepository urRep;
        /// <summary>
        /// 用户仓储
        /// </summary>
        IUserRepository uRep;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志</param>
        /// <param name="urRep">用户与角色关联仓储</param>
        public UserRoleService(ILogger<UserRoleService> logger,
         IUserRoleRepository urRep,
          IUserRepository uRep
         )
        {
            this.logger = logger;
            this.urRep = urRep;
            this.uRep = uRep;
        }

        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public async Task<int> ByAddUserRole(List<int> Ids, int Rid)
        {
            try
            {
                var urinfo = new UserRole();
                var liy = 0;
                foreach (var item in Ids)
                {
                    if (item != 0)
                    {
                        var qouen = await urRep.GetAsync(p => p.Rid == Rid && p.Uid == item &&p.deleteFlag==false);
                        if (qouen.Count == 0)
                        {
                            urinfo.URid = 0;
                            urinfo.Rid = Rid;
                            urinfo.Uid = item;

                            liy += await urRep.AddAsync(urinfo);
                        }
                    }
                }
                return liy;
            }
            catch (Exception ex)
            {
                logger.LogError("【用户与角色服务层】: 添加用户与角色 出错" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 删除用户与角色
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public async Task<int> DelUserRole(int Uid, int Rid)
        {
            try
            {
                var liy = 0;

                var qouen = await urRep.GetAsync(p => p.Rid == Rid && p.Uid == Uid && !p.deleteFlag);
                
                foreach (var item1 in qouen)
                {
                    item1.deleteFlag = true;
                    liy += await urRep.UpdateAsync(item1);
                }

                return liy;
            }
            catch (Exception ex)
            {
                logger.LogError("【用户与角色服务层】: 删除用户与角色 出错" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 根据部门显示用户
        /// </summary>
        /// <param name="Ids">部门编号集合</param>
        /// <returns></returns>
        public async Task<List<Tmeen>> GetUserinfo(string Ids)
        {
            try
            {
                var tmen = new List<Tmeen>();
                var list = Ids.Split(",");
                foreach (var item in list)
                {
                    if (Convert.ToInt32(item) != 0)
                    {
                        var qouen = await uRep.GetAsync(p => p.department == Convert.ToInt32(item));
                        foreach (var item1 in qouen)
                        {
                            tmen.Add(new Tmeen
                            {
                                id = item1.uId,
                                label = item1.uName
                            });
                        };
                    }
                }
                return tmen;
            }
            catch (Exception ex)
            {
                logger.LogError("【用户与角色服务层】: 根据部门显示用户 出错" + ex.Message);
                throw;
            }

        }
        /// <summary>
        /// 根据角色显示
        /// </summary>
        /// <param name="Rid">角色编号</param>
        /// <returns></returns>
        public async Task<List<UserInfo>> GetRoleUserinfo(int Rid)
        {
            try
            {
                var list = (from ur in await urRep.GetAllAsync()
                            join u in await uRep.GetAllAsync()
                            on ur.Uid equals u.uId
                            where ur.Rid == Rid && ur.deleteFlag==false
                            select u).ToList();
                return list;
            }
            catch (Exception ex)
            {
                logger.LogError("【用户与角色服务层】: 根据角色显示 出错" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 反填用户角显示(部门)
        /// </summary>
        /// <param name="Rid"></param>
        /// <returns></returns>
        public async Task<List<int>> Backfillde(int Rid)
        {
            try
            {
                var list = Backfilluid(Rid);
                var delist = new List<int>();
                foreach (var item in await list)
                {
                    var ll = await uRep.GetAsync(p => p.uId == item);
                    foreach (var itemk in ll)
                    {
                        delist.Add(itemk.department);

                    }
                }
                delist = delist.Distinct().ToList();

                return delist;
            }
            catch (Exception ex)
            {
                logger.LogError("【用户与角色服务层】: 反填用户角色显示 出错" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 反填用户角色显示（用户）
        /// </summary>
        /// <param name="Rid">角色</param>
        /// <returns></returns>
        public async Task<List<int>> Backfilluid(int Rid)
        {
            try
            {
                var list = (from ur in await urRep.GetAllAsync()
                            join u in await uRep.GetAllAsync()
                            on ur.Uid equals u.uId
                            where ur.Rid == Rid && ur.deleteFlag == false
                            select u).ToList();
                var uidlist = new List<int>();

                foreach (var item in list)
                {
                    uidlist.Add(item.uId);
                }
                return uidlist;
            }
            catch (Exception ex)
            {
                logger.LogError("【用户与角色服务层】: 反填用户角色显示 出错" + ex.Message);
                throw;
            }
        }


    }
}
